package com.cdwang.websocket_module;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;


import com.cdwang.websocket_module.websocket.JWebSocketClient;
import com.cdwang.websocket_module.websocket.JWebSocketClientService;
import com.cdwang.websocket_module.websocket.SendInfo;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * copyright (C), 2022, 运达科技有限公司
 * fileName WebSocketUtils
 *
 * @author 王玺权
 * date 2022-10-21 11:16
 * description websocket连接方法
 * history
 */
public enum  WebSocketUtils {
    /**
     * 单例
     */
    @SuppressLint("StaticFieldLeak") INSTANCE;
    private   Context mContext;
    public  void initData(Context Context, SendInfo sendInfo){
        this.mContext=Context;
        this.mSendInfo=sendInfo;
        startJWebSClientService();
        bindService();
    }

    private JWebSocketClient client;
    private SendInfo mSendInfo;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;

    /**
     * 启动服务（websocket客户端服务）
     */
    private  void startJWebSClientService() {
        Intent intent = new Intent(mContext, JWebSocketClientService.class);
        mContext.startService(intent);

    }


    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(mContext, JWebSocketClientService.class);
        mContext.bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("MainActivity", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            jWebSClientService.setSendInfo(mSendInfo);
            client = jWebSClientService.client;
            jWebSClientService.setActivity((Activity) mContext);
//            jWebSClientService.setSendInfo(mSendInfo);



        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("MainActivity", "服务与活动成功断开");
        }
    };
}
